package com.hjx.movie.core.security.auth;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

/**
 * <p>Title:</p>
 * <p>Description:</p>
 *
 * @author hjx
 * @date 2020/6/10 - 9:08
 */
@Slf4j
@Component("rbacService")
public class RBACService {
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    //判断某用户是否具有该请求资源的访问权限
    public boolean  hasPermission(HttpServletRequest request, Authentication authentication){
        //从authentication中获取在认证时保存的用户信息
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails){
            UserDetails userDetails = (UserDetails) principal;
            //从用户信息中获取出权限信息
            Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
            //获取用户要访问的uri
            String uri = request.getRequestURI();
            //将用户要访问的uri与用户所拥有的权限做对比 通过则证明该用户拥有访问该uri的权限
            for (GrantedAuthority g:authorities){
                // 原来为 antPathMatcher.matchStart(g.getAuthority()+"/**", uri); 现在进行了修改
                final boolean result = antPathMatcher.matchStart(g.getAuthority(), uri);
                log.debug("用户权限:{} 访问接口:{} 匹配结果:{}",g.getAuthority(),uri,result);
                if (result){
                    log.debug("鉴权成功,UID为{}的用户拥有访问{}的权限",userDetails.getUsername(),uri);
                    return true;
                }
            }
        }
        log.debug("鉴权失败");
        return false;
    }
}
